<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>排序算法之计数排序</title>
</head>
<body>
  <script type="text/javascript">
    function countSort(arr) {
      // 1.得到数列的最大值
      let max = arr[0];
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] > max) {
          max = arr[i];
        }
      }
      // 2.根据数列最大值确定统计数组的长度
      const countArr = new Array(max + 1).fill(0);
      // 3.遍历数列，填充统计数组
      for (let i = 0; i < arr.length; i++) {
        countArr[arr[i]]++;
      }
      //4.遍历统计数组，输出结果
      let index = 0;
      for (let i = 0; i < countArr.length; i++) {
        if (countArr[i] > 0) {
          arr[index++] = i;
        }
      }
    }

    const arr = [10, 6, 3, 4, 8, 1, 2];
    countSort(arr);
    console.log(arr);
  </script>
</body>
</html>